package com.java.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @ClassName: BaseDao
* @Description: 数据库驱动连接基础类
* @author ChenJiaLu
* @date 2023年12月29日 上午10:13:52
*
 */
public class BaseDao {
	private static final String IP        = "127.0.0.1";  
	private static final String PORT      = "3306";  
	private static final String DB        = "hospital";  
	private static final String USERNAME  = "root";  
    private static final String USERPSW   = "root";
    /**
     * lib包有两个mysql驱动，根据自己数据库版本选择导入不同的驱动吧
     * com.mysql.jdbc.Driver:    <= MySQL Connector/J 5.1
     * com.mysql.cj.jdbc.Driver: >= MySQL Connector/J 8.0 
     */
    private static final String DRIVER    = "com.mysql.jdbc.Driver";  
	private Connection connection;  
    private Statement statement;  
  
    public BaseDao() {
		try {
		    Class.forName(DRIVER);  
		    String DATABASE_URL = "jdbc:mysql://"+IP+":"+PORT+"/"+DB+"?useUnicode=true&characterEnconding=UTF-8"; 
		    setConnection(DriverManager.getConnection(DATABASE_URL, USERNAME, USERPSW));  
		    statement = getConnection().createStatement();
		} catch (ClassNotFoundException | SQLException e) {
		    e.printStackTrace();  
		}
    }  
  
    // 查询数据  
    public ResultSet query(String sql) throws SQLException {
        return statement.executeQuery(sql);  
    }  
  
    // 插入数据  
    public void insert(String sql) throws SQLException {
        statement.executeUpdate(sql);  
    }  
  
    // 更新数据  
    public void update(String sql) throws SQLException {  
        statement.executeUpdate(sql);  
    }  
  
    // 删除数据  
    public void delete(String sql) throws SQLException {  
        statement.executeUpdate(sql);  
    }  
  
    // 关闭连接和语句对象  
    public void close() {
    	try {
    		if (statement != null) {  
                statement.close();  
            }  
            if (getConnection() != null) {  
                getConnection().close();  
            }
		} catch (SQLException e) {
			e.printStackTrace();
		}  
    }

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}
}
